<template>
    <div id="Login">
        <el-form
            :model="userForm"
            label-width="auto"
            class="userForm"
            size="default"
            :rules="rules"
        >
            <h2 class="title no-select">后台登录</h2>
            <el-form-item label="用户名" prop="username">
                <el-input v-model.trim="userForm.username" placeholder="请输入用户名">
                    <template #prefix>
                        <i class="iconfont icon-yonghu-yuan" />
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input
                    v-model.trim="userForm.password"
                    type="password"
                    show-password
                    placeholder="请输入登录密码"
                >
                    <template #prefix>
                        <i class="iconfont icon-mima" />
                    </template>
                </el-input>
            </el-form-item>
            <el-button type="primary" round @click="handleLogin">登录</el-button>
        </el-form>
    </div>
</template>

<script setup>
import { reactive } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
const store = useStore()
const router = useRouter()
const userForm = reactive({
    username: 'zhangsan',
    password: 'zhangsan666'
})

// 表单校验
const rules = reactive({
    username: [
        { required: true, message: '用户名不能忘呐~', trigger: 'blur' },
        { min: 3, message: '名字最少三个字', trigger: 'blur' },
        { pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '不可包含特殊字符' }
    ],
    password: [
        { required: true, message: '密码也是必须的哟~', trigger: 'blur' },
        { pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '不可包含特殊字符' }
    ]
})

// 处理登录
const handleLogin = async () => {
    if (!userForm.username && !userForm.password) return false
    const res = await $api.userLogin({ username: userForm.username, password: userForm.password })
    ElMessage.success(`登录成功，欢迎回来 ${res.username}`)
    store.commit('saveUserInfo', res)
    router.push('/')
}


</script>

<style lang='less' >
#Login {
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: var(--bgColor1);
    .userForm {
        padding: 10px 30px 20px;
        border-radius: 5px;
        display: flex;
        flex-flow: column;
        box-shadow: 0 0 10px 1px var(--bgColor4);
        background-color: var(--bgColor2);
        .title {
            text-align: center;
            line-height: 2;
            margin-bottom: 10px;
            color: var(--color1);
        }
        .iconfont {
            margin-left: -3px;
        }
    }
}
label {
    color: var(--color2) !important;
}
.el-button {
    background-color: var(--bgColor1);
    border-color: var(--bgColor4);
    color: var(--color3);
}
</style>
